package com.zhou.common.operator.log.core.resolver.impl;

import com.zhou.common.operator.log.core.model.ClientInfo;
import com.zhou.common.operator.log.core.resolver.ClientInfoResolver;
import com.zhou.common.operator.log.core.util.IpUtil;
import eu.bitwalker.useragentutils.UserAgent;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletRequest;

@Slf4j
public class DefaultClientInfoResolver implements ClientInfoResolver {

    @Override
    public ClientInfo resolveClientInfo(HttpServletRequest request) {
        String userAgentString = request.getHeader("User-Agent");
        UserAgent agent = UserAgent.parseUserAgentString(userAgentString);
        ClientInfo clientInfo = new ClientInfo();
        if (agent.getOperatingSystem() != null) {
            clientInfo.setOs(agent.getOperatingSystem().getName());
        }

        if (agent.getBrowser() != null) {
            clientInfo.setBrowser(agent.getBrowser().getName());
        }

        if (agent.getBrowserVersion() != null) {
            clientInfo.setBrowserVersion(agent.getBrowserVersion().getVersion());
        }
        clientInfo.setClientIp(IpUtil.parseClientIp(request));
        clientInfo.setServerIp(IpUtil.localIp());
        return clientInfo;
    }
}
